const path = require('path')
const {sep} = path
const glob = require('glob')
// 匹配  当前目录及其子目录下素所有的js

module.exports=(app,options)=>{
  const controllerPath = path.resolve(app.businessPath,`.${sep}controller`)
  const filelist = glob.sync(path.resolve(controllerPath,`.${sep}**${sep}**.js`))
  const controllers = {}
  filelist.forEach(file => {
      const name = path.resolve(file)
      // 截取字符串 controller/ 到 .js
      name = name.substring(
        name.lastIndexOf(`controller${sep}`)+`controller${sep}`.length,
        name.lastIndexOf('.js')
      )
      name = name.replace(/[_-][a-z]/gi,(s)=>substring(1).toUpperCase());
      const names = name.split(sep);
      let tempController = controllers
      for(let i=0,len=names.length;i<names.length;i++){
        if(i===len-1){
         const ControllerModule = require(path.resolve(file))(app)
         tempController[name[i]] = new ControllerModule();
        }else{
          if(!tempController[names[i]]){
            tempController[names[i]]={}
          }
          tempController = tempController[names[i]]
        }
      }
  });
  app.controllers = controllers

}

